#include "../model/osdutilsmodel.h"
#include "../model/osdremoteservicemodel.h"
#include "../control/callcontroller.h"
#include "../control/msgpagecontroller.h"
#include "meetcontrolpage.h"
#include "ui_meetcontrolpage.h"
#include "callcontrolpanel.h"
#include <QKeyEvent>
#include <QDateTime>
#include <QPainter>
#include "../remoteservice/remoteerr.h"
#include "../remoteservice/statinfo.h"
#include "meetpageworker.h"
#include "../control/mainwindowcontroller.h"
#include "../control/indexpagecontroller.h"
#include "../sys/sysconfighandler.h"
#include "viewglobal.h"
#include <QDebug>
#include "../event/senddocevent.h"
#include "../event/sendlocalevent.h"
#include "../event/sendsoundevent.h"
#include "../event/sendvedioevent.h"
#include "../event/showconnevent.h"
#include "../event/controlmenuevent.h"

#define PAGE_LEFT ((QObject*)3)         //向左翻页
#define PAGE_RIGHT ((QObject*)4)        //向右翻页
#define DOWN_FOCUS ((QObject*)5)        //向下移交焦点

#define MAX_LINE       (10)

MeetControlPage::MeetControlPage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MeetControlPage),
    curPage(0),
    maxPage(1)
{
    ui->setupUi(this);

    m_ctrlpanel = new CallControlPanel(this);
    ui->control_layout->addWidget(m_ctrlpanel);
    m_ctrlpanel->hide();

    initFocusOrder();

    worker = new MeetPageWorker;
    connect(this, SIGNAL(updatePanel()), worker, SLOT(work()));

    connect(&CallController::instance(), SIGNAL(loseFocusSig()), this, SLOT(aquireFocus()));
    connect(&CallController::instance(), SIGNAL(exitSig()), this, SLOT(exit()));
    connect(&CallController::instance(), SIGNAL(showInfoSig(bool)), this, SLOT(showConnectInfo(bool)));
    connect(&CallController::instance(), SIGNAL(updateCellNameSig(QString)), this, SLOT(updateCellName(QString)));


    connect(&OSDRemoteServiceModel::instance(), SIGNAL(notifyLeaveConference(BaseResp)), this, SLOT(exitSlot(BaseResp)));

    ui->widInfo->installEventFilter(this);

//    this->setAutoFillBackground(false);
    this->setWindowFlags(Qt::FramelessWindowHint);
    this->setAttribute(Qt::WA_TranslucentBackground,true);

    m_directs[0] = ui->lblDirect1;
    m_directs[1] = ui->lblDirect2;
    m_directs[2] = ui->lblDirect3;
    m_directs[3] = ui->lblDirect4;
    m_directs[4] = ui->lblDirect5;
    m_directs[5] = ui->lblDirect6;
    m_directs[6] = ui->lblDirect7;
    m_directs[7] = ui->lblDirect8;
    m_directs[8] = ui->lblDirect9;
    m_directs[9] = ui->lblDirect10;
    m_protocols[0] = ui->lblProtocol1;
    m_protocols[1] = ui->lblProtocol2;
    m_protocols[2] = ui->lblProtocol3;
    m_protocols[3] = ui->lblProtocol4;
    m_protocols[4] = ui->lblProtocol5;
    m_protocols[5] = ui->lblProtocol6;
    m_protocols[6] = ui->lblProtocol7;
    m_protocols[7] = ui->lblProtocol8;
    m_protocols[8] = ui->lblProtocol9;
    m_protocols[9] = ui->lblProtocol10;
    m_callrates[0] = ui->lblCallrate1;
    m_callrates[1] = ui->lblCallrate2;
    m_callrates[2] = ui->lblCallrate3;
    m_callrates[3] = ui->lblCallrate4;
    m_callrates[4] = ui->lblCallrate5;
    m_callrates[5] = ui->lblCallrate6;
    m_callrates[6] = ui->lblCallrate7;
    m_callrates[7] = ui->lblCallrate8;
    m_callrates[8] = ui->lblCallrate9;
    m_callrates[9] = ui->lblCallrate10;
    m_resolutins[0] = ui->lblVideoResolutin1;
    m_resolutins[1] = ui->lblVideoResolutin2;
    m_resolutins[2] = ui->lblVideoResolutin3;
    m_resolutins[3] = ui->lblVideoResolutin4;
    m_resolutins[4] = ui->lblVideoResolutin5;
    m_resolutins[5] = ui->lblVideoResolutin6;
    m_resolutins[6] = ui->lblVideoResolutin7;
    m_resolutins[7] = ui->lblVideoResolutin8;
    m_resolutins[8] = ui->lblVideoResolutin9;
    m_resolutins[9] = ui->lblVideoResolutin10;
    m_fpss[0] = ui->lblVideoFPS1;
    m_fpss[1] = ui->lblVideoFPS2;
    m_fpss[2] = ui->lblVideoFPS3;
    m_fpss[3] = ui->lblVideoFPS4;
    m_fpss[4] = ui->lblVideoFPS5;
    m_fpss[5] = ui->lblVideoFPS6;
    m_fpss[6] = ui->lblVideoFPS7;
    m_fpss[7] = ui->lblVideoFPS8;
    m_fpss[8] = ui->lblVideoFPS9;
    m_fpss[9] = ui->lblVideoFPS10;
    m_loses[0] = ui->lblLose1;
    m_loses[1] = ui->lblLose2;
    m_loses[2] = ui->lblLose3;
    m_loses[3] = ui->lblLose4;
    m_loses[4] = ui->lblLose5;
    m_loses[5] = ui->lblLose6;
    m_loses[6] = ui->lblLose7;
    m_loses[7] = ui->lblLose8;
    m_loses[8] = ui->lblLose9;
    m_loses[9] = ui->lblLose10;
    m_safes[0] = ui->lblSafe1;
    m_safes[1] = ui->lblSafe2;
    m_safes[2] = ui->lblSafe3;
    m_safes[3] = ui->lblSafe4;
    m_safes[4] = ui->lblSafe5;
    m_safes[5] = ui->lblSafe6;
    m_safes[6] = ui->lblSafe7;
    m_safes[7] = ui->lblSafe8;
    m_safes[8] = ui->lblSafe9;
    m_safes[9] = ui->lblSafe10;

    m_icons[0] = ui->icon1;
    m_icons[1] = ui->icon2;
    m_icons[2] = ui->icon3;
    m_icons[3] = ui->icon4;
    m_icons[4] = ui->icon5;
    m_icons[5] = ui->icon6;
    m_icons[6] = ui->icon7;
    m_icons[7] = ui->icon8;
    m_icons[8] = ui->icon9;
    m_icons[9] = ui->icon10;

    m_cellNames[0] = ui->lblCellName1;
    m_cellNames[1] = ui->lblCellName2;
    m_cellNames[2] = ui->lblCellName3;
    m_cellNames[3] = ui->lblCellName4;
    m_cellNames[4] = ui->lblCellName5;
    m_cellNames[5] = ui->lblCellName6;
    m_cellNames[6] = ui->lblCellName7;
    m_cellNames[7] = ui->lblCellName8;
    m_cellNames[8] = ui->lblCellName9;
    m_cellNames[9] = ui->lblCellName10;

    for(int i = 0; i < MAX_LINE;i++)
    {
        m_protocols[i]->hide();
        m_safes[i]->hide();
        m_cellNames[i]->hide();
    }
}

MeetControlPage::~MeetControlPage()
{
    workThread.quit();
    workThread.wait();
    delete ui;
}

void MeetControlPage::clearLabels()
{
    for(int i = 0; i < MAX_LINE; i++)
    {
        m_directs[i]->setText("");
        m_protocols[i]->setText("");
        m_callrates[i]->setText("");
        m_resolutins[i]->setText("");
        m_fpss[i]->setText("");
        m_loses[i]->setText("");
        m_safes[i]->setText("");
        m_icons[i]->clear();
    }
}

void MeetControlPage::initFocusOrder()
{
    QList<QObject*> orderlist;
    orderlist.clear();
    orderlist<< NULL << DOWN_FOCUS << PAGE_LEFT << PAGE_RIGHT;
    m_ctrlOrder.insert(ui->widInfo, orderlist);
}

bool MeetControlPage::eventFilter(QObject *o, QEvent *e)
{
    if (e->type() == QEvent::KeyRelease)
    {
        QKeyEvent *ke = dynamic_cast<QKeyEvent*>(e);
        if (ke && (ke->key() == Qt::Key_Right
                   || ke->key() == Qt::Key_Down
                   || ke->key() == Qt::Key_Left
                   || ke->key() == Qt::Key_Up))
        {
            if (!m_ctrlOrder.contains(o))
            {
                return false;
            }

            QObject *target = m_ctrlOrder.value(o).at(OSDUtilsModel::instance().keyIndex(ke->key()));
            if (target)
            {
                if (target == DOWN_FOCUS)
                {
                    CallController::instance().aquireFocus();
                }
                else if (target == PAGE_LEFT)
                {
                    //左翻页
                    if (curPage == 0)
                    {
                        return true;
                    }
                    curPage -= 1;
                    showPage(curPage);
                } else if (target == PAGE_RIGHT)
                {
                    //右翻页
                    if (curPage == (maxPage-1) )
                    {
                        return true;
                    }
                    curPage += 1;
                    showPage(curPage);

                } else {
                    QWidget* w = dynamic_cast<QWidget*>(target);
                    if (w) w->setFocus();
                }
            }
            return true;
        }
    }else if (e->type() == QEvent::KeyPress)
    {
        return true;
    }else if (e->type() == SendLocalEvent::eventType)
    {
        m_ctrlpanel->changeLocalShow();
        e->accept();
        return true;
    } else if (e->type() == SendSoundEvent::eventType)
    {
        m_ctrlpanel->changeSound();
        e->accept();
        return true;
    } else if (e->type() == SendVedioEvent::eventType)
    {
        m_ctrlpanel->changeVedio();
        e->accept();
        return true;
    } else if (e->type() == SendDocEvent::eventType)
    {
        m_ctrlpanel->changeDoc();
        e->accept();
        return true;
    } else if (e->type() == ShowConnEvent::eventType)
    {
        m_ctrlpanel->showConnInfo();
        e->accept();
        return true;
    } else if (e->type() == ControlMenuEvent::eventType)
    {
        if (m_ctrlpanel->isVisible())
        {
            qDebug() << "ctrl panel hide!";
            m_ctrlpanel->hide();
        }
        else
        {
            qDebug() << "ctrl panel show!";
            m_ctrlpanel->show();
        }
        e->accept();
        return true;
    }
    return false;
}

void MeetControlPage::keyReleaseEvent(QKeyEvent *e)
{
    if (e->key() == Qt::Key_Escape)
    {
        if (m_ctrlpanel->isVisible())
        {
            qDebug() << "ctrl panel hide!";
            m_ctrlpanel->hide();
        }
        else
        {
            qDebug() << "ctrl panel show!";
            m_ctrlpanel->show();
        }
        return;
    }
    QWidget::keyReleaseEvent(e);
}

bool MeetControlPage::event(QEvent *e)
{
    return QWidget::event(e);
}

void MeetControlPage::aquireFocus()
{
    if (ui->page_details->isVisible())
    {
        ui->widInfo->setFocus();
    }
}

void MeetControlPage::reset()
{
    ui->stackedWidget->setCurrentWidget(ui->page_meet);
}

void MeetControlPage::showConnectInfo(bool s)
{
    if (s)
    {
        ui->stackedWidget->setCurrentWidget(ui->page_details);
    }
    else
    {
        ui->stackedWidget->setCurrentWidget(ui->page_meet);
        return;
    }

    QMap<QString,QString> rateMap;
    rateMap.insert("1024","1M");
    rateMap.insert("2048","2M");
    rateMap.insert("4096","4M");
    rateMap.insert("6144","6M");
    rateMap.insert("8192","8M");
    //设置呼叫速率
    ui->lblCallrate->setText(rateMap.value(SysConfigHandler::instance().callRate(),
                                           SysConfigHandler::instance().callRate()));

    //刷新面板信息
    m_statList = m_ctrlpanel->statList();

    qDebug() << m_statList;

    if (m_statList.count() == 0)
    {
        return;
    }
    //获取信息
    if ((m_statList.count() % MAX_LINE) == 0)
    {
        maxPage = m_statList.count()/MAX_LINE;
    }
    else
    {
        maxPage = m_statList.count()/MAX_LINE+1;
    }
    //显示第1页
    showPage(0);
}

void MeetControlPage::updateCellName(QString data)
{
    QStringList dataList;
    int cellNum = 0;
    QString name;
    int x = 0;
    int y = 0;
    QStringList cellInfoList;

    if (data.size() > 0) {
        dataList = data.split("#");
        cellNum = dataList.size();
    }
    
    for(int i = 0; i < cellNum; i++)
    {
        cellInfoList = dataList[i].split(",");
        name = cellInfoList[0];
        x = cellInfoList[1].toInt();
        y = cellInfoList[2].toInt();
        m_cellNames[i]->setText(name);
        m_cellNames[i]->adjustSize();
        m_cellNames[i]->move(x + 6, y + 6);
        m_cellNames[i]->show();
    }
    for(int i = cellNum; i < MAX_LINE; i++)
    {
        m_cellNames[i]->hide();
        m_cellNames[i]->setText("");
    }
}

void MeetControlPage::showEvent(QShowEvent *e)
{
    reset();
    emit updatePanel();
    QWidget::showEvent(e);
    m_ctrlpanel->setFirstFocus();
    m_ctrlpanel->hide();
}

void MeetControlPage::hideEvent(QHideEvent *e)
{
    QWidget::hideEvent(e);
}

void MeetControlPage::showPage(int page)
{
    clearLabels();

    int startIndex = page*MAX_LINE;
    int len = qMin((m_statList.count()-startIndex),MAX_LINE);

    QList<QList<QString> > m = m_statList.mid(startIndex,len);
    for(int i = 0; i < m.count(); i++)
    {
        QList<QString> v = m_statList.at(i);
        m_directs[i]->setText(v.value(0,""));
        m_protocols[i]->setText(v.value(1,""));
        m_callrates[i]->setText(v.value(2,""));
        m_resolutins[i]->setText(v.value(3,""));
        m_fpss[i]->setText(v.value(4,""));
        m_loses[i]->setText(v.value(5,""));
        m_safes[i]->setText(v.value(6,""));
        QString pixmap = (v.value(7,"") == "up") ? ":/img/uparrow.png" : ":/img/downarrow.png";
        m_icons[i]->setPixmap(QPixmap(pixmap));
    }
}

void MeetControlPage::refreshPanel(bool s,
                                   bool v,
                                   bool d,
                                   bool l)
{
    qDebug() << "meeting:" << s << "," << v <<"," << d << "," << l;
    m_ctrlpanel->setShowLocalStatus(s);
    m_ctrlpanel->setDocStatus(v);
    m_ctrlpanel->setSoundStatus(d);
    m_ctrlpanel->setVedioStatus(l);
}


void MeetControlPage::exitSlot(BaseResp rv)
{
    if (rv.getIsSuccess())
    {
        IndexPageController::instance().resetUi();
        MainWindowController::instance().changeTopPage(OSD::ViewGlobal::TOP_PAGE_MAIN_WINDOW);
    }
    else
    {
        MsgPageController::instance().showMsg(rv.getCodeString());
    }
}
void MeetControlPage::exit()
{
    OSDRemoteServiceModel::instance().leaveConference();
}

void MeetControlPage::timerHandle() {
    ui->time_label->setText(QDateTime::currentDateTime().toString("HH:mm"));
}

void MeetControlPage::paintEvent(QPaintEvent *e)
{
    Q_UNUSED(e);

    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);//绘制样式
}
